<?php

class EProduct extends DataObject {

    static $db = array(
        'Title' => 'Varchar(255)',
        'UrlSegment' => 'Varchar(255)',
        'CreatedDate' => 'SS_Datetime',
        'UpdateDate' => 'SS_Datetime',
        'Content' => 'HTMLText',
        'Blurb' => 'HTMLText',
        'View' => 'Int',
        'Price' => 'Int',
        'WarrantyDuration' => 'Int',
        'Featured' => 'Boolean',
        'Publish' => 'Boolean',
        'SortOrder' => 'Int'
    );

    static $has_one = array(
        'Image' => 'Image'
    );

    static $has_many = array(
        'EProductImages' => 'EProductImage',
    );

    static $many_many = array(
        'ECategories' => 'ECategory',
        'RelatedProducts' => 'EProduct'
    );

    static $searchable_fields = array(
        'Title', 'UrlSegment', 'Publish'
    );

    static $defaults = array('View' => 0, 'Publish' => true);
    static $singular_name = 'Product';

    public static $default_sort = 'SortOrder';

    function getCMSFields() {
        $fields = parent::getCMSFields();
        $categories = ECategory::get()->map('ID', 'Title')->toArray();
        asort($categories);

        $categoryField = new ListboxField('ECategories', 'Add Category', $categories);
        $categoryField->setMultiple(true);

        $fields->removeByName('ECategories');
        $fields->removeByName('EProducts');

        $fields->addFieldToTab('Root.Main', new UploadField('Image', 'Image (230x170)'));
        $fields->addFieldToTab('Root.Main', new TextField('Title', 'Title'));
        $fields->addFieldToTab('Root.Main', new TextField('UrlSegment', 'Url Segment'));
        $fields->addFieldToTab('Root.Main', $categoryField);

        $fields->addFieldToTab('Root.Main', new TextField('Price','Price'));
        $fields->addFieldToTab('Root.Main', new TextField('WarrantyDuration','Warranty Duration'));


        $arrProducts = EProduct::get()->map('ID', 'Title')->toArray();
        asort($arrProducts);

        $relatedField = new ListboxField('RelatedProducts', 'Related', $arrProducts);
        $relatedField->setMultiple(true);
        $fields->addFieldToTab('Root.Main', $relatedField);

        $fields->addFieldToTab('Root.Main', new CheckboxField('Featured', 'Featured'));
        $fields->addFieldToTab('Root.Main', new ReadonlyField('CreatedDate', 'Created Date'));
        $fields->addFieldToTab('Root.Main', new ReadonlyField('UpdateDate', 'Update Date'));
        $fields->addFieldToTab('Root.Main', new ReadonlyField('View', 'View'));
        $fields->addFieldToTab('Root.Main', new CheckboxField('Publish', 'Publish'));
        $fields->addFieldToTab('Root.Main', new HiddenField('SortOrder'));

        $blurb = new HtmlEditorField('Blurb','Blurb');
        $blurb->setRows(3);
        $fields->findOrMakeTab('Root.InfoTab', 'Info');
        $fields->addFieldsToTab('Root.InfoTab', array(
            $blurb,
            new HtmlEditorField('Content', 'Content')
        ));

        return $fields;
    }

    function onBeforeWrite() {
        parent::onBeforeWrite();

        if($this->Title == null || $this->Title == ''){
            $this->Title  = 'product-'.$this->ID;
        }

        if ($this->ID == 0) {
            $this->CreatedDate = date('Y-m-d H:i:s');
            $this->UpdateDate  = date('Y-m-d H:i:s');
        }else{
            $this->UpdateDate  = date('Y-m-d H:i:s');
        }

        if($this->UrlSegment == null || $this->UrlSegment == ''){
            $this->UrlSegment = $this->checkUniqueUrlSegment(SiteTree::create()->generateURLSegment($this->Title));
        }else{
            $this->UrlSegment = $this->checkUniqueUrlSegment(SiteTree::create()->generateURLSegment($this->UrlSegment));
        }

    }

    static $summary_fields = array(
        'thumb' => 'Image',
        'Title' => 'Title',
        'Price' => 'Price',
        'Featured' => 'Featured',
//        'CreatedDate' => 'CreatedDate',
//        'UpdateDate' => 'UpdateDate',
        'summary_category' => 'Category',
        'Publish' => 'Publish'
    );

    function summary_category(){
        $categories = $this->ECategories()->map('Title')->toArray();
        return implode(', ', $categories);
    }

    function thumb() {
        return $this->ImageID != 0 ? $this->Image()->CMSThumbnail() : 'no-image';
    }

    function checkUniqueUrlSegment($url_segment){

        $products = EProduct::get()->filter(array('UrlSegment' => $url_segment));

        $num = time();

        if($products->Count() > 0){
            if($products->Count() == 1){
                $product = $products->first();
                if( $product->ID == $this->ID ){
                    return $url_segment;
                }else{
                    return $url_segment . '-' . $num;
                }
            }else{
                return $url_segment . '-' . $num;
            }
        }
        return $url_segment;

    }

    function ProductLink(){
        $params = Controller::curr()->request->params();

        if($params['Controller'] == 'EpalShop_Controller'){
            $category_segment = $params['ID'];
            if($category_segment == null){
                $category = ECategory::get()->first();
                return EpalShop_Controller::$URLCategory.'/'.$category->UrlSegment.'/'.$this->UrlSegment;
            }else{
                $category = ECategory::get()->filter(array('UrlSegment' => $category_segment))->first();
                return EpalShop_Controller::$URLCategory.'/'.$category->UrlSegment.'/'.$this->UrlSegment;
            }
        }

        $category = $this->ECategories()->first();
        return EpalShop_Controller::$URLCategory.'/'.$category->UrlSegment.'/'.$this->UrlSegment;
    }

    function ProductHolderLink(){
        $catg = $this->ECategories()->first();
        if($catg){
            $productHolder = $catg->EpalProductHolders()->first();
            if( $productHolder ){
                return $productHolder->Link();
            }
        }
        return null;
    }

    function PriceVND(){
        return number_format($this->Price);
    }

}